//
//  MineViewController.m
//  Tunnel
//
//  Created by wbb on 2022/3/8.
//

#import "MineViewController.h"
#import "MineNotifyVC/MineNotifyVC.h"
#import "MineCell.h"
#import "User.h"
#import "TYGlobal.h"
#import "SDWebImage/SDWebImage.h"
#import "JPUSHService.h"


@interface MineHeaderView  : TYBaseView
@property (nonatomic, strong) UIImageView * headerImgView;
@property (nonatomic, strong) UILabel * nameLabel;
@property (nonatomic, strong) UILabel * deptLabel;

-(void)loadData:(User*)user;
@end

@implementation MineHeaderView

- (instancetype)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
        [self initUI];
    }
    return self;
}

- (void)initUI {
    UIImageView *headerImgView = [[UIImageView alloc] init];
    headerImgView.image = [UIImage imageNamed:@"mine_header_icon"];
    [self addSubview:headerImgView];
    self.headerImgView = headerImgView;
    [headerImgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(30);
        make.centerY.offset(0);
        make.width.height.offset(44);
    }];
    
    UILabel *nameLabel = [[UILabel alloc] init];
    nameLabel.text = @"wbb";
    nameLabel.font = [UIFont systemFontOfSize:14];
    nameLabel.textColor = [UIColor whiteColor];
    [self addSubview:nameLabel];
    self.nameLabel = nameLabel;
    [nameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(headerImgView.mas_right).offset(10);
        make.bottom.equalTo(headerImgView.mas_centerY).offset(-2.5);
    }];
    
    UILabel *deptLabel = [[UILabel alloc] init];
    deptLabel.text = @"单位";
    deptLabel.font = [UIFont systemFontOfSize:14];
    deptLabel.textColor = hexColor(C3E2FF);
    [self addSubview:deptLabel];
    self.deptLabel = deptLabel;
    [deptLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(headerImgView.mas_right).offset(10);
        make.top.equalTo(headerImgView.mas_centerY).offset(2.5);
    }];
}
-(void)loadData:(User*)user{
    [self.headerImgView sd_setImageWithURL:[NSURL URLWithString:user.avatar] placeholderImage:[UIImage imageNamed:@"mine_header_icon"]];
    self.nameLabel.text = user.nickName;
    self.deptLabel.text = user.userType;
}
@end


@interface MineViewController ()<UITableViewDelegate, UITableViewDataSource>
@property (nonatomic, strong) UITableView * tableView;
@property (nonatomic, strong) MineHeaderView * headerView;
@property (nonatomic, copy) NSArray * dataArr;
@property (nonatomic, assign) NSInteger logoutRetryCount;

@end

@implementation MineViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationItem.title = @"我的";
    self.view.backgroundColor = [UIColor blueColor];
     self.logoutRetryCount = 0; // 初始化计数
    self.dataArr = @[
        @{
            @"imgName": @"mine_notif",
            @"title": @"通知设置",
            @"toPath": @""
        },
        @{
            @"imgName": @"mine_logout",
            @"title": @"注销登录",
            @"toPath": @""
        }
    ];
    
    [self initUI];
 
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    AppDelegate *delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    [delegate getUnReadNum];
    kWEAK_SELF;
    [TYNetWorkTool getRequest:TYGetUserInfoAPI parameters:@{} successBlock:^(BOOL success, NSDictionary * _Nonnull data, NSString * _Nonnull msg) {
        if(success){
            User * user = [User yy_modelWithJSON:data[@"data"]];
            [weakSelf.headerView loadData:user];
        }
    } failureBlock:^(NSString * _Nonnull description) {
        
    }];
    
}
- (void)initUI {
    
    self.view.backgroundColor = hexColor(F6F7F9);
    
    UIImageView *bgImgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, kSCREEN_WIDTH, kSCREEN_WIDTH * 232.f/375)];
    bgImgView.image = [UIImage imageNamed:@"mine_nav_bg"];
    [self.view addSubview:bgImgView];
    
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(12);
        make.right.offset(-12);
        make.bottom.top.offset(0);
    }];
    
    MineHeaderView *headerView = [[MineHeaderView alloc] initWithFrame:CGRectMake(0, 0, kSCREEN_WIDTH - 24, 98)];
    self.headerView = headerView;
    self.tableView.tableHeaderView = headerView;
}

#pragma mark - UITableViewDelegate, UITableViewDataSource ----
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArr.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return 44;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *cellIdentifier = @"MineCell";
    MineCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (!cell) {
        cell = [[MineCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }
    
    // 获取总行数
    NSInteger totalRows = [tableView numberOfRowsInSection:indexPath.section];
    
    // 设置圆角
    [cell setCornerForIndexPath:indexPath totalRows:totalRows dataSource:self.dataArr];
    
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) {
        [self.navigationController pushViewController:[MineNotifyVC new] animated:NO];
    }else if (indexPath.row == 1){
        [self logout];
        [TYGlobal logout];
        
        
    }
    
}
// 退出登录方法内部
- (void)logout {
    kWEAK_SELF
    [JPUSHService setAlias:@"" completion:^(NSInteger iResCode, NSString *iAlias, NSInteger seq) {
        if (iResCode == 0) {
            NSLog(@"别名清除成功");
            // 执行后续退出逻辑（清除本地数据、跳转登录页等）
        } else {
            weakSelf.logoutRetryCount++;
            if (weakSelf.logoutRetryCount < 3) { // 限制最多重试3次
                NSLog(@"重试清除别名（第%ld次）", (long)weakSelf.logoutRetryCount);
                [weakSelf logout];
            } else {
                NSLog(@"多次失败，放弃重试");
                // 可提示用户“退出失败，请稍后再试”
            }
        }
    } seq:[WDGlobal shareInstance].uuid];
    // 其他退出登录逻辑，像清除本地用户数据等
}

#pragma mark ---- lazy ----
- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    }
    return _tableView;
}
@end


